package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.common.result.AjaxResult;
import com.crm.common.result.Result;
import com.crm.common.utils.CurrentHolder;
import com.crm.domain.Dept;


import com.crm.domain.DeptTreeResult;
import com.crm.dto.DeptListDto;
import com.crm.dto.Vo.DeptListVo;
import com.crm.dto.Vo.DeptTreeVo;
import com.crm.mapper.DeptMapper;
import com.crm.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptMapper deptmapper;


/**
 * 删除部门
 * */
    @Override
    public AjaxResult deleteDept(Long id) {
        log.info("删除部门 id:{}", id);
        deptmapper.deleteId(id);
        return AjaxResult.success();
    }
/**
 *
 * 更新部门
 * */
    @Override
    public AjaxResult updateDept(Dept dept) {
        dept.setUpdatedBy(CurrentHolder.getCurrentId() + "");
        dept.setUpdateTime(LocalDateTime.now());
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dept::getDeptId, dept.getDeptId());
        deptmapper.update(dept, wrapper);
        return AjaxResult.success();
    }

/**
 *
 *  添加部门
 * */
    @Override
    public AjaxResult addDept(Dept dept) {

        dept.setCreateBy(CurrentHolder.getCurrentId()+"");
        dept.setUpdatedBy(CurrentHolder.getCurrentId()+"");
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptmapper.insert(dept);
        return AjaxResult.success();
    }

/**
 *  * 部门列表查询
 * */
    @Override
    public AjaxResult queryDeptList(DeptListDto dto) {
        //mybatis plus
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        //如果名字不为空，则模糊查询
        wrapper.like(null != dto.getDeptName(), Dept::getDeptName, dto.getDeptName());
        //如果状态不为空，则精确查询
        wrapper.eq(null != dto.getStatus(), Dept::getStatus, dto.getStatus());
        //按照orderNum升序排序
        wrapper.orderByAsc(Dept::getOrderNum);
        //用MybatisPlus执行查询数据库，获取部门列表。
        List<Dept> depts = deptmapper.selectList(wrapper);
        //如果查询结果为空则返回错误信息没找着任何部门信息
        if (CollectionUtils.isEmpty(depts)) {
            return AjaxResult.error("未找到任何部门信息");
        }
        //将部门列表转换为部门列表视图对象DeptListVo
        List<DeptListVo> deptListvos = new ArrayList<>(depts.size());
        for (Dept dept : depts) {
            DeptListVo deptListVo = new DeptListVo();
            BeanUtils.copyProperties(dept, deptListVo);
            deptListvos.add(deptListVo);
        }
        return AjaxResult.success(deptListvos);
    }

    /**
     *
     * 部门树形结构查询
     * */
    @Override
    public DeptTreeResult roleDeptTreeselect(Long roleId) {
        List<Dept> deptList = deptmapper.selectList(null);
        List<Long> list = deptList.stream().map(Dept::getDeptId).toList();
        int list1 = Integer.parseInt(list.toString());
        List<DeptTreeVo> deptTreeVos = buildDeptTree(deptList, 0L);
        return DeptTreeResult.success(deptTreeVos, Collections.singletonList(list1));
    }
/**
 *   部门详情查询
 * */
    @Override
    public AjaxResult queryDept(Long id) {
        Dept dept = deptmapper.selectByIds(id);
        if (dept != null) {
            DeptListVo deptListVo = new DeptListVo();
            BeanUtils.copyProperties(dept, deptListVo);
            return AjaxResult.success(deptListVo);
        }
        return AjaxResult.error("查询失败");
    }

    @Override
    public List<DeptTreeVo> treeSelect() {
        return deptmapper.treeSelect();

    }

    // 将扁平列表转换为树状结构的方法
    public List<DeptTreeVo> buildDeptTree(List<Dept> depts, Long parentId) {
        // 过滤出当前 parentId 下的 Dept 对象并映射为 DeptTreeVo
        List<DeptTreeVo> children = depts.stream()
                .filter(dept -> dept.getParentId() == parentId)
                .map(dept -> {
                    DeptTreeVo node = new DeptTreeVo();
                    node.setId(dept.getDeptId());
                    node.setLabel(dept.getDeptName());

                    // 递归设置当前节点的子节点
                    node.setChildren(buildDeptTree(depts, dept.getDeptId()));

                    return node;
                })
                .collect(Collectors.toList());

        return children;
    }
}















